package com.yunyi.ne.netty;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyWebSocketClient {

    private final Channel channel;
    private final String serverUrl;

    public NettyWebSocketClient(Channel channel, String serverUrl) {
        this.channel = channel;
        this.serverUrl = serverUrl;
    }

    public void sendMessage(String message) {
        if (channel.isActive()) {
            try {
                channel.writeAndFlush(new TextWebSocketFrame(message));
            } catch (Exception e) {
                System.out.println("Error sending message: " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            System.out.println("Channel to " + serverUrl + " is not active. Unable to send message.");
        }
    }

    public void close() throws InterruptedException {
        channel.closeFuture().sync();
    }
}